﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using wojilu.Apps.Qycms.Domain;
using wojilu.IO;
using wojilu.Members.Interface;
using wojilu.Members.Sites.Domain;
using wojilu.Members.Sites.Service;
using wojilu.Members.Users.Domain;
using wojilu.Web.Controller.Common;
using wojilu.Web.Mvc.Attr;

namespace wojilu.Web.Controller.Admin.Qycms
{
    public class FileController : BaseController
    {
        public virtual IAdminLogService<SiteLog> logService { get; set; }

        public FileController()
        {
            logService = new SiteLogService();
        }

        private void setpublic()
        {
            User user = ctx.viewer.obj as User;
            var modelPowerGroup = PowerGroup.findById(user.GroupId);
            bind("powergroup", modelPowerGroup);
        }

        [HttpGet, HttpPost]
        public virtual void FileList()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            var dirlist = ctx.Get("dirlist");
            var filedir = ctx.Get("filedir");
            Configs config = Configs.find("valname=:v").set("v", "upfile_dir").first();
            var dt = FileSystemObject.GetDirectoryInfos(sys.Path.Root  + config.value + dirlist, FsoMethod.All);
            var dv = dt.DefaultView;
            dv.Sort = "lastWriteTime desc";
            dt = dv.ToTable();
            dt.Columns.Add("fid", typeof(String));
            dt.Columns.Add("url", typeof(String));
            Configs c = Configs.find("valname=:v").set("v", "upfile_dir").first();
            set("filepath", c.value);
            var c1 = Configs.find("valname=:v").set("v", "domain").first();
            set("adminurl", c1.value);
            foreach (DataRow row in dt.Rows)
            {
                var url = strUtil.Join(strUtil.Join(strUtil.Join(c1.value, c.value), dirlist), row["name"].ToString());
                var fid = DESEncrypt.Encrypt(url, 1);
                row["fid"] = fid;
                row["url"] = url;
            }
            var Count = dt.Rows.Count;
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(dt.Rows.Count.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", dt);
            var updirtype = 0;
            if (!dirlist.StrIsNullOrEmpty())
            {
                updirtype = 1;
            }
            else
            {
                updirtype = 2;
            }
            if (updirtype == 1)
            {
                var strArray = dirlist.SplitString("/");
                var str = strArray[strArray.Length - 2] + "/";
                str = Left(dirlist, dirlist.Length - str.Length);
                set("uploadurl", to(FileList) + "?filedir=" + filedir + "&dirlist=" + str);
            }
            set("uploadurl1", to(FileList) + "?filedir=" + filedir + "&dirlist=" + dirlist);
            set("updirtype", updirtype);
            set("dirlist", dirlist);
        }

        [HttpGet]
        public virtual void FileMkDir()
        {
            SetPublic();
            setpublic();
            target(FileMkDirDo);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");

        }

        [HttpPost]
        public virtual void FileMkDirDo()
        {
            var path = ctx.Post("path");
            var dirname = ctx.Post("dirname");
            Configs c = Configs.find("valname=:v").set("v", "upfile_dir").first();
            var FileUrl = sys.Path.Root + c.value + path;
            FileSystemObject.Create(PathHelper.Map(FileUrl + dirname), FsoMethod.Folder);
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void DelFile()
        {
            var Ids = ctx.Post("selectinfoid");
            var path = ctx.Post("path");
            var strArray = Ids.SplitString(",");
            Configs c = Configs.find("valname=:v").set("v", "upfile_dir").first();
            for (int i = 0; i < strArray.Length - 1; i++)
            {
                if (strArray[i].IndexOf(".") > -1)
                {
                    FileSystemObject.Delete(PathHelper.Map(strUtil.Join(strUtil.Join(strUtil.Join(sys.Path.Root , c.value) , path) , strArray[i])), FsoMethod.File);
                }
                else
                {
                    FileSystemObject.Delete(PathHelper.Map(strUtil.Join(strUtil.Join(strUtil.Join(sys.Path.Root , c.value) , path) , strArray[i])), FsoMethod.Folder);
                }
            }
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void ImageCrop()
        {
            SetPublic();
            setpublic();
            target(ImgageCut);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            var dir = ctx.Get("dir");
            var filename = ctx.Get("filename");
            set("imgname", filename);
            var type = ctx.Get("type");
            Configs c = Configs.find("valname=:v").set("v", "upfile_dir").first();
            var path = c.value + dir;
            set("path", path);
            Image image = Image.FromFile(PathHelper.Map(sys.Path.Root + path + filename));
            var srcW = image.Width;
            set("srcW", srcW);
            var srcH = image.Height;
            set("srcH", srcH);
            var strArray = filename.SplitString(".");
            var imgname = strArray[0] + "_imagecrop." + strArray[1];
            set("newfilename", imgname);
            var c1 = Configs.find("valname=:v").set("v", "domain").first();
            var url = strUtil.Join(strUtil.Join(strUtil.Join(c1.value, c.value), dir), filename);
            set("url", url);
            image.Dispose();
        }

        [HttpPost]
        public virtual void ImgageCut()
        {
            var path = ctx.Post("path");
            var imgname = ctx.Post("imgname");
            var imgW = ctx.PostInt("imgW");
            var imgH = ctx.PostInt("imgH");
            var selecton = ctx.PostInt("selecton");
            var newimagename = ctx.Post("newimagename");
            var dstW = ctx.PostInt("dstW");
            var dstH = ctx.PostInt("dstH");
            var w = ctx.PostInt("w");
            var h = ctx.PostInt("h");
            var x = ctx.PostInt("x");
            var y = ctx.PostInt("y");
            var filepath = sys.Path.Root + path + imgname;
            var newfilepath = sys.Path.Root + path + newimagename;
            ResetImg(PathHelper.Map(filepath), dstW, dstH, x, y, w, h, PathHelper.Map(newfilepath));
            if (selecton == 1)
            {
                FileSystemObject.Delete(PathHelper.Map(filepath), FsoMethod.File);
                FileSystemObject.Move(PathHelper.Map(newfilepath), PathHelper.Map(filepath), FsoMethod.File);
            }
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void RenameDir()
        {
            SetPublic();
            setpublic();
            target(RenameDirDo);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
        }

        [HttpPost]
        public virtual void RenameDirDo()
        {
            var dir = ctx.Post("dir");
            var filename = ctx.Post("filename");
            var type = ctx.Post("type");
            var newfilename = ctx.Post("newfilename");
            var FileUrl = sys.Path.Root + configsService.GetValue("upfile_dir") + dir;
            if (type == "dir")
            {
                FileSystemObject.Move(PathHelper.Map(FileUrl + filename), PathHelper.Map(FileUrl + newfilename), FsoMethod.Folder);
            }
            else
            {
                var ExtName = wojilu.Utils.GetFileExtName(filename);
                FileSystemObject.Move(PathHelper.Map(FileUrl + filename), PathHelper.Map(FileUrl + newfilename + "." + ExtName), FsoMethod.File);
            }
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        public void ResetImg(string ImgFile, int PicWidth, int PicHeight, int PointX, int PointY, int CutWidth, int CutHeight, string toImgFile)
        {
            Image imgPhoto = Image.FromFile(ImgFile);
            Bitmap bmPhoto = new Bitmap(CutWidth, CutHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
            gbmPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, CutWidth, CutHeight), PointX * imgPhoto.Width / PicWidth, PointY * imgPhoto.Height / PicHeight, CutWidth * imgPhoto.Width / PicWidth, CutHeight * imgPhoto.Height / PicHeight, GraphicsUnit.Pixel);

            bmPhoto.Save(toImgFile, imgPhoto.RawFormat);

            imgPhoto.Dispose();
            gbmPhoto.Dispose();
            bmPhoto.Dispose();
        }

    }
}
